﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Asn1.X509;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class SettlementDetailInterfaceBusiness_A : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        public List<OL_FilterDTO> Filters;
        public SettlementDetailInterfaceBusiness_A()
        {
            this.InterfaceName = "亚马逊结算明细_佣金计算";
            //获取字段的映射关系
            tableField = GetMapField("getFilterRows");
            //索引字段
            Keys = GetKeys("getFilterRows");
            indexFields.Add(Keys.Where(x => x.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();


            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //执行查询前添加过滤条件
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }

        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            try
            {
                //数据库连接
                ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

                //获取此接口的所有API信息
                this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
                Base_InterfaceOption queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
                Base_InterfaceOption insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
                Base_InterfaceOption upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
                Base_InterfaceOption deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API

                //获取SKU信息
                //OL_LocalSKUInterfaceBusiness oL_LocalSKUInterface = new OL_LocalSKUInterfaceBusiness();
                //oL_LocalSKUInterface.Filters.Add(//    //13:>,14>=15:<,16<=
                //                                     new OL_FilterDTO() { ControlId = "678762cc9e0bc69bf1c9ca84", DataType = 6, SpliceType = 1, FilterType = 8, Value = "" });//计算佣金不为空的项
                //List<LocalSKU> skuList = await oL_LocalSKUInterface.QueryAsync<LocalSKU>(oL_LocalSKUInterface.queryOption, oL_LocalSKUInterface.tableField, oL_LocalSKUInterface.SqlDb);





                //获取源数据
                SettlementDetailInterfaceBusiness settlementDetailInterfaceBusiness = new SettlementDetailInterfaceBusiness();
                List<SettlementDetail> sourceData_s = new List<SettlementDetail>();//目标据集合
                settlementDetailInterfaceBusiness.Filters.Clear();
                //      settlementDetailInterfaceBusiness.Filters.Add(
                //    //13:>,14>=15:<,16<=
                //    new OL_FilterDTO() { ControlId = "675f83e79e0bc69bf198799c", DataType = 15, SpliceType = 1, FilterType = 14, Value = DateTime.Now.AddDays(-50).ToString("yyyy-MM-dd") } //过滤结算时间条件
                //);
                settlementDetailInterfaceBusiness.Filters.Add(
              //13:>,14>=15:<,16<=
              new OL_FilterDTO() { ControlId = "675f83e79e0bc69bf198799c", DataType = 15, SpliceType = 1, FilterType = 14, Value = DateTime.Now.AddDays(-100).ToString("yyyy-MM-dd") } //过滤结算时间条件
          );
                sourceData_s = await settlementDetailInterfaceBusiness.QueryAsync<SettlementDetail>(settlementDetailInterfaceBusiness.queryOption, settlementDetailInterfaceBusiness.tableField, settlementDetailInterfaceBusiness.SqlDb);
                sourceData_s.ForEach(x => x.ID = x.amazonOrderId + x.storeName + x.sellerSku + x.postedDateLocale + x.eventType);

                //获取源数据
                List<SettlementDetail> sourceData_Convert = sourceData_s.GroupBy(x => x.ID).Select(x =>
                {
                    var pri = x.Where(y => y.type == "Principal");
                    if (!pri.IsNullOrEmpty() || pri.Count() > 0) return pri.First();
                    else return x.First();
                }).ToList();



                //将行维度参数转成列维度
                foreach (var item1 in sourceData_Convert)
                {
                    if (item1.type == "Principal")
                    {
                        List<SettlementDetail> items = sourceData_s.Where(x => x.ID == item1.ID).ToList();

                        //主费用/数量
                        var principals = items.Where(x => x.type == "Principal");
                        if (!principals.IsNullOrEmpty() || principals.Count() > 0)
                        {
                            item1.quantity = principals.Sum(x => x.quantity.ToInt()).ToString();
                            item1.Principal = principals.Sum(x => x.currencyAmount.ToDouble()).ToString();
                        }
                        //促销折扣
                        var promotionDiscounts = items.Where(x => x.type == "PromotionDiscount");
                        if (!promotionDiscounts.IsNullOrEmpty() || promotionDiscounts.Count() > 0)
                        {
                            item1.PromotionDiscount = promotionDiscounts.Sum(x => x.currencyAmount.ToDouble()).ToString();
                        }

                        //佣金
                        var commissions = items.Where(x => x.type == "Commission");
                        if (!commissions.IsNullOrEmpty() || commissions.Count() > 0)
                        {
                            item1.Commission = commissions.Sum(x => x.currencyAmount.ToDouble()).ToString();
                        }

                        //退货佣金
                        var retCommissions = items.Where(x => x.type == "RefundCommission");
                        if (!retCommissions.IsNullOrEmpty() || retCommissions.Count() > 0)
                        {
                            item1.RetCommission = retCommissions.Sum(x => x.currencyAmount.ToDouble()).ToString();
                        }

                        //佣金标准
                        //var retCommissions = skuList.Where(x => x. == "RefundCommission");
                        //if (!retCommissions.IsNullOrEmpty() || retCommissions.Count() > 0)
                        //{
                        //    item1.RetCommission = retCommissions.Sum(x => x.currencyAmount.ToDouble()).ToString();
                        //}

                    }
                }
                List<SettlementDetail> sourceData = sourceData_Convert.Where(x => !x.amazonOrderId.IsNullOrEmpty() && !x.Principal.IsNullOrEmpty()).ToList();//目标据集合

                //获取目标数据
                this.Filters.Clear();
                this.Filters.Add(
              //13:>,14>=15:<,16<=
              new OL_FilterDTO() { ControlId = "675f83e79e0bc69bf198799c", DataType = 15, SpliceType = 1, FilterType = 14, Value = DateTime.Now.AddDays(-100).ToString("yyyy-MM-dd") } //过滤结算时间条件
          );
                List<SettlementDetail> targetData = await this.QueryAsync<SettlementDetail>(queryOption, this.tableField, this.SqlDb);




                if (this.State > 0 && sourceData.Count > 0)
                {
                    //更新
                    #region
                    List<SettlementDetail> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<SettlementDetail>(Keys, "RowId")).ToList();//获取交集(更新项)
                    List<OL_RowDTO> updataData = ConvertOL_Row(updataItem, tableField);//需要更新的数据集合
                    ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                    #endregion

                    //新增
                    #region
                    List<SettlementDetail> insertItem = sourceData.Except(targetData, new ComparerFromKey<SettlementDetail>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                    List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                    ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                    #endregion

                    //删除
                    #region
                    List<SettlementDetail> deleteItem = targetData.Except(sourceData, new ComparerFromKey<SettlementDetail>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)
                    List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                    ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行
                    #endregion
                }
                else
                {
                    throw new NotImplementedException("目标/源查询无数据无法执行接口!!");

                }
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }


        public void SetCurrencyAmountCount(List<SettlementDetail> sourceData, SettlementDetail item1, bool isReturn, double commissionStandard)
        {

            //佣金=金额-促销折扣*0.12
            //如果退货，退货佣金＝订单佣金*20%≥5，5，＜5，订单佣金*20%
            double commission;//佣金
            double returnCommission;//主费用
            double principal;//促销折扣
            double returnPrincipal;//退货佣金
            double promotionDiscount; //退货主费用
            double returnPromotionDiscount;//退货促销折扣

            if (isReturn)
            {
                ////佣金
                //var commission_s = targetData.Where(x => x.amazonOrderId == item1.amazonOrderId && x.postedDateLocale == item1.postedDateLocale && x.type == "Commission" && x.currencyAmount.ToDouble() < 0).ToList().First().currencyAmount;
                //commission = commission_s.ToDouble();
                ////主费用
                //var principal_s = targetData.Where(x => x.amazonOrderId == item1.amazonOrderId && x.postedDateLocale == item1.postedDateLocale && x.type == "Principal" && x.currencyAmount.ToDouble() > 0).ToList().First().currencyAmount;
                //principal = principal_s.ToDouble();
                ////促销折扣
                //var promotionDiscount_s = targetData.Where(x => x.amazonOrderId == item1.amazonOrderId && x.postedDateLocale == item1.postedDateLocale && x.type == "PromotionDiscount" && x.currencyAmount.ToDouble() < 0).ToList().First().currencyAmount;
                //promotionDiscount = promotionDiscount_s.IsNullOrEmpty() ? 0 : promotionDiscount_s.ToDouble();


                //退货佣金
                var ComList = sourceData.Where(x => x.amazonOrderId == item1.amazonOrderId && x.postedDateLocale == item1.postedDateLocale && x.type == "Commission" && x.currencyAmount.ToDouble() > 0).ToList();
                var returnCommission_s = ComList.Count > 0 ? ComList.First().currencyAmount : "0";
                returnCommission = returnCommission_s.ToDouble();
                //退货主费用
                var PriList = sourceData.Where(x => x.amazonOrderId == item1.amazonOrderId && x.postedDateLocale == item1.postedDateLocale && x.type == "Principal" && x.currencyAmount.ToDouble() < 0).ToList();
                var returnPrincipal_s = PriList.Count > 0 ? PriList.First().currencyAmount : "0";

                returnPrincipal = returnPrincipal_s.ToDouble();
                //退货促销折扣
                var PDList = sourceData.Where(x => x.amazonOrderId == item1.amazonOrderId && x.postedDateLocale == item1.postedDateLocale && x.type == "PromotionDiscount" && x.currencyAmount.ToDouble() > 0).ToList();
                var returnPromotionDiscount_s = PDList.Count > 0 ? PDList.First().currencyAmount : "0";
                returnPromotionDiscount = returnPromotionDiscount_s.ToDouble();

                //计算退货手续费
                var temp = returnCommission * 0.2;
                string currencyAmount_count = (temp >= 5 ? 5 : temp).ToString();
                sourceData.Where(x => x.amazonOrderId == item1.amazonOrderId && x.postedDateLocale == item1.postedDateLocale && x.type == "RefundCommission").ForEach(x => x.CountCommission = currencyAmount_count);

                ////如果是部分退
                //if (principal + returnPrincipal > 0)
                //{
                //    //计算佣金
                //    string currencyAmount_count = ((principal + promotionDiscount) * commissionStandard).ToString();
                //    targetData.Where(x => x.amazonOrderId == item1.amazonOrderId && x.postedDateLocale == item1.postedDateLocale && x.currencyAmount.ToDouble() < 0 && x.type == "Commission").ForEach(x => x.currencyAmount_count = currencyAmount_count);

                //    //计算退货佣金
                //    currencyAmount_count = ((returnPrincipal + returnPromotionDiscount) * commissionStandard).ToString();
                //    targetData.Where(x => x.amazonOrderId == item1.amazonOrderId && x.postedDateLocale == item1.postedDateLocale && x.currencyAmount.ToDouble() > 0 && x.type == "Commission").ForEach(x => x.currencyAmount_count = currencyAmount_count);

                //    //计算退货手续费
                //    var temp = returnCommission * 0.2;
                //    currencyAmount_count = (temp >= 5 ? 5 : temp).ToString();
                //    targetData.Where(x => x.amazonOrderId == item1.amazonOrderId && x.postedDateLocale == item1.postedDateLocale && x.type == "RefundCommission").ForEach(x => x.currencyAmount_count = currencyAmount_count);


                //}
                ////如果是全退
                //else
                //{
                //    //计算退货手续费
                //    var temp = returnCommission * 0.2;
                //    string currencyAmount_count = (temp >= 5 ? 5 : temp).ToString();
                //    targetData.Where(x => x.amazonOrderId == item1.amazonOrderId && x.postedDateLocale == item1.postedDateLocale && x.type == "RefundCommission").ForEach(x => x.currencyAmount_count = currencyAmount_count);
                //}

            }
            else
            {
                //佣金
                var ComList = sourceData.Where(x => x.amazonOrderId == item1.amazonOrderId && x.postedDateLocale == item1.postedDateLocale && x.type == "Commission").ToList();
                if (ComList.Count > 0)
                {
                    var commission_s = ComList.Count > 0 ? ComList.First().currencyAmount : "0";
                    commission = commission_s.ToDouble();

                    //主费用
                    var PriList = sourceData.Where(x => x.amazonOrderId == item1.amazonOrderId && x.postedDateLocale == item1.postedDateLocale && x.type == "Principal").ToList();
                    var principal_s = PriList.Count > 0 ? PriList.First().currencyAmount : "0";
                    principal = principal_s.ToDouble();
                    //促销折扣
                    var PDlist = sourceData.Where(x => x.amazonOrderId == item1.amazonOrderId && x.postedDateLocale == item1.postedDateLocale && x.type == "PromotionDiscount").ToList();
                    var promotionDiscount_s = PDlist.Count > 0 ? PDlist.First().currencyAmount : "0";
                    promotionDiscount = promotionDiscount_s.ToDouble();
                    //计算佣金赋值
                    string currencyAmount_count = ((principal + promotionDiscount) * commissionStandard).ToString();
                    sourceData.Where(x => x.amazonOrderId == item1.amazonOrderId && x.postedDateLocale == item1.postedDateLocale && x.type == "Commission").ForEach(x => x.CountCommission = currencyAmount_count);
                }
            }


        }




        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value))
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
